import React from 'react';
import { SpinnerIcon } from '../../../icons/SpinnerIcon';
import styles from './Select.module.css';

export interface SelectOption {
    value: string;
    label: string;
}

export interface SelectProps extends Omit<React.SelectHTMLAttributes<HTMLSelectElement>, 'onChange'> {
    label?: string;
    options: SelectOption[];
    error?: string;
    onChange?: (value: string) => void;
    loading?: boolean;
    actionButton?: React.ReactNode;
}

export const Select: React.FC<SelectProps> = ({
    label,
    options,
    error,
    className,
    onChange,
    loading,
    actionButton,
    ...props
}) => {
    const handleChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
        onChange?.(event.target.value);
    };

    return (
        <div className={styles.formGroup}>
            {label && <label className={styles.label}>{label}</label>}
            <div className={styles.selectWrapper}>
                {loading && (
                    <div className={styles.loading}>
                        <SpinnerIcon size={16} color="currentColor" />
                    </div>
                )}
                <select
                    className={`${styles.select} ${error ? styles.error : ''} ${loading ? styles.loading : ''} ${className || ''}`}
                    onChange={handleChange}
                    disabled={loading || props.disabled}
                    {...props}
                >
                    {options.map((option) => (
                        <option key={option.value} value={option.value}>
                            {option.label}
                        </option>
                    ))}
                </select>
                {actionButton}
            </div>
            {error && (
                <div className={styles.errorMessage}>
                    {error}
                </div>
            )}
        </div>
    );
};